// Initialize app
var myApp = new Framework7({
    //template7Pages: true, //enable Template7 rendering for pages
    //Specify templates/pages data
    precompileTemplates: true,
    template7Pages: true,
});
// If we need to use custom DOM library, let's save it to $$ variable:
var $$ = Framework7.$;

// Add view
var mainView = myApp.addView('.view-main', {
    // Because we want to use dynamic navbar, we need to enable it for this view:
    dynamicNavbar: true,
})

var currentPage = 1;
var alreadyAlert = true;
var queryParas = {
    PageSize: 10,
    PageNumber: 1,
}

$$(document).on('pageAfterAnimation', function (e) {
   App.pageAfterAnimation(e.detail.page.name);
});

$$(document).on('pageInit', function (e) {
    // Get page data from event data
    var page = e.detail.page;
    if (page.name === 'index') {
        onEvent();
        addSearchResult(queryParas, "refresh");
    }else if(page.name === 'seller-shop'){
        App.loadSellerShop();
    } else if (page.name === 'detail') {
        App.loadDetailPage();
    }else if(page.name === 'reserve'){
        var typeId =App.judgeType($("#detail-typeId").val());
        if(typeId == 23 || typeId == 13){
            App.loadTicketReservePage();
        }else if(typeId == 24 || typeId == 15){
            App.loadCharteredReservePage();
        }

        /*var toolbarHtml = '<div class="toolbar-inner" style="text-align: center;padding:0px">' +
            '<a style="font-size: 16px;color:#343434;margin-left:1%">总额：<label id="orderAmount" style="color:red">0</label>元</a>' +
            '<a id="ticket-reserve" style="width:45%;height:60px;background-color: #509AF1;line-height: 60px;color: #FFFFFF;">现在预定</a>' +
            '</div>';
        $("#index-tool").html(toolbarHtml);
        var typeId= App.judgeType($("#detail-typeId").val());
        $("#reserve-ticket-amount").on("change", function () {
            var tt = $("#reserve-ticket-amount").val() * ($("#ticket-detail-price").html().replace("￥", ""));
            $("#orderAmount").html(tt);
        })

        /!*var path = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx1a5d74a8c7cb135e&redirect_uri=http%3a%2f%2f15z6868x01.51mypc.cn%2fmulan_xxl%2fadmin%2ftest%2fgetAuthority&response_type=code&scope=snsapi_base&state=123#wechat_redirect";*!/
        $("#ticket-reserve").on("click", function () {
            App.showLoading();
            var amount = $("#reserve-ticket-amount").val();
            var mobile = $("#reserve-ticket-mobile").val();
            var remarks = $("#reserve-ticket-remarks").val();
            var couponCode = $("#reserve-ticket-coupon").val();
            var ticketId = $("#detail-targetId").val();
            var para = {
                amount: amount,
                mobileNumber: mobile,
                couponCode: couponCode,
                targetId: ticketId,
                typeId: typeId,
                remarks: remarks
            }
            $.post(Constant.contextUrl + '/mulanweb/wechat/order/save', para, function (info) {
                if (info.message || info.AlertMessage) {
                    Constant.alertMessage( info.message,info.AlertMessage);
                }
                if (info.returnCode == 1) {
                    var target = info.target;
                    mainView.router.load({url: "../../menu2/ticket/confirm_pay.jsp?price=" + target.price + "&title=" + target.title + "&targetLogo=" + info.targetLogo + "&orderNumber=" + info.orderNumber});
                }
                App.hideLoading();
            });
        });*/
    }else if(page.name === 'confirm_pay'){
        mainView.hideToolbar();
    }
})

function onEvent() {
    var para = {
        PageSize: 10,
        PageNumber: 1,
    };
    //上拉无限加载
    var loading = false;
    // 添加'infinite'监听器
    $$('.infinite-scroll').on('infinite', function () {
        if (loading) return;
        // 设置flag
        loading = true;
        currentPage = currentPage + 1;
        para.PageNumber = currentPage;
        addSearchResult(para);
        loading = false;
    });

    // 添加'refresh'监听器
    $$('.pull-to-refresh-content').on('refresh', function (e) {
        para.PageNumber = 1;
        para.PageSize = 10;
        if (!alreadyAlert) {
            alreadyAlert = true;
            var html = '<div class="infinite-scroll-preloader">' +
                '<div class="preloader" style="margin-left:48%"></div>' +
                '</div>';
            $$('.page-content').append(html);
        }
        $$('div[name=items]').remove();
        addSearchResult(para, "refresh")
        myApp.pullToRefreshDone();
    });
}

var totalPage = 1;
function addSearchResult(para, AddType) {
    if (para.PageNumber > totalPage) {
        if (alreadyAlert) {
            Constant.alertNotification("往下已没有更多内容了，刷新试试！");
            $$('.infinite-scroll-preloader').remove();
            alreadyAlert = false;
        }
        return false;
        App.hideLoading();
    }
    $.ajax({
        url: Constant.ctx("/mulanweb/common/order/searchUserOrder"),
        async: false,
        type: "post",
        dataType: "json",
        data: para,
        success: function (data) {
            if (data.ReturnCode == 1) {
                var tt = {}
                for (var i in data) {
                    tt[i] = data[i];
                    if (i == "DataList") {
                        var html = '<span style="float:right;color:#666666;font-size: 14px;">已过期</span>';
                        for (y in data["DataList"]) {
                            var buttonName = ""
                            var statusId = tt[i][y].order.statusId;
                            var typeId = tt[i][y].order.typeId;
                            var targetId = tt[i][y].order.targetId;
                            var orderNumber =tt[i][y].order.orderNumber;
                            if (statusId == 4) {
                                buttonName = "查看兑换码";
                                html = '<button type="button" onclick="clickType('+statusId+','+typeId+','+targetId+',\''+orderNumber+'\')" style="float:right;width:auto;height:27px;font-size: 14px;color:#509AF1;background-color:white;line-height: 100%;border:1px solid #509AF1;border-radius: 4px">' + buttonName + '</button>';
                                html = html + '<div style="height:2px;width:30px;float:right"></div><button type="button" onclick="applyRefund('+'\''+orderNumber+'\')" style="float:right;width:auto;height:27px;font-size: 14px;color:#509AF1;background-color:white;line-height: 100%;border:1px solid #509AF1;border-radius: 4px">申请退款</button>';
                            } else if (statusId == 5) {
                                buttonName = "点击支付";
                                html = '<button type="button" onclick="clickType('+statusId+','+typeId+','+targetId+',\''+orderNumber+'\')" style="float:right;width:auto;height:27px;font-size: 14px;color:#509AF1;background-color:white;line-height: 100%;border:1px solid #509AF1;border-radius: 4px">' + buttonName + '</button>';
                                html = html + '<div style="height:2px;width:30px;float:right"></div><button type="button" onclick="cancelOrder('+'\''+orderNumber+'\')" style="float:right;width:auto;height:27px;font-size: 14px;color:#509AF1;background-color:white;line-height: 100%;border:1px solid #509AF1;border-radius: 4px">取消订单</button>';
                            } else if (statusId == 6) {
                                html = '<span style="float:right;color:#666666;font-size: 14px;">已过期</span>';
                            } else if (statusId == 7) {
                                buttonName = "点击评论";
                                html = '<button type="button" onclick="clickType('+statusId+','+typeId+','+targetId+',\''+orderNumber+'\')" style="float:right;width:auto;height:27px;font-size: 14px;color:#509AF1;background-color:white;line-height: 100%;border:1px solid #509AF1;border-radius: 4px">' + buttonName + '</button>';
                            } else if (statusId == 8) {
                                buttonName = "查看评论";
                                html = '<button type="button" onclick="clickType('+statusId+','+typeId+','+targetId+',\''+orderNumber+'\')" style="float:right;width:auto;height:27px;font-size: 14px;color:#509AF1;background-color:white;line-height: 100%;border:1px solid #509AF1;border-radius: 4px">' + buttonName + '</button>';
                            }else if(statusId == 9){
                                html = '<span style="float:right;color:#666666;font-size: 14px;">已退款</span>';
                            }else if(statusId == 23){
                                html = '<span style="float:right;color:#666666;font-size: 14px;">办理中</span>';
                            }else if(statusId == 24){
                                html = '<span style="float:right;color:#666666;font-size: 14px;">已完成</span>';
                            }else{
                                html="";
                            }
                            tt[i][y].order["buttonName"] = html;
                        }
                    }
                }
                var template = $('#orderSearchDataList').html();
                var compiledTemplate = Template7.compile(template);
                var htmlStr = compiledTemplate(data);
                totalPage = data.TotalPage;
                if (AddType) {
                    $("#queryResultList").html(htmlStr);
                    currentPage = 1;
                } else {
                    $("#queryResultList").append(htmlStr);
                }
                if(data.TotalPage <= data.PageNumber || !data.TotalPage){
                    $$('.infinite-scroll-preloader').remove();
                }
                totalPage = data.TotalPage;
            }else{
                if(data.TotalPage <=data.PageNumber || (!data.TotalPage)){
                    $$('.infinite-scroll-preloader').remove();
                }
            }
            App.hideLoading();
        }
    }, para, function (data) {
    });
}

function clickType(statusId,typeId,targetId,orderNumber) {
    myApp.showPreloader('请求中......');
    if (statusId == 4) {
        //查看兑换码
        var para = {
            typeId:typeId,
            targetId:targetId,
            orderNumber:orderNumber
        }
        $.post(Constant.ctx('/mulanweb/common/order/getUserVerifyCode'), para, function (info) {
            if (info.ReturnCode == 1) {
                var code = info.ReturnStr;
                var modal = myApp.modal({
                    text: '<div style="padding-top:150px;text-align: center;background:url(../../../static/image/order/modelBackground-1x.png) no-repeat 0px 0px ; width:270px; height: 226px;">' +
                    '<span style="font-size: 14px;color:#323232;">兑换码</span><br/>' +
                    '<span style="font-size: 26px;color:#39383D;">'+code+'</span>' +
                    '</div>',
                    buttons: [
                        {
                            text: '确定'
                        }
                    ]
                });
            }else{
                myApp.alert(info.ReturnStr,'新西兰微助手');
            }
        });
    } else if (statusId == 5) {
        //点击支付
        callpay(orderNumber);
    } else if (statusId == 7) {
        //点击评论
        var modal = myApp.modal({
            text: '<div style="padding:140px 20px 0px 20px;text-align: center;background:url(../../../static/image/order/modelBackground-1x.png) no-repeat 0px 0px ; width:270px; height: 320px;">' +
            '<div style="width:100%;height:25px" id="order-content-evaluate">'+
            '<img src="'+Constant.cdnContentPath+'/static/image/detail/collection2-2x-false.png" width="30px"/>'+
            '<img src="'+Constant.cdnContentPath+'/static/image/detail/collection2-2x-false.png" width="30px"/>'+
            '<img src="'+Constant.cdnContentPath+'/static/image/detail/collection2-2x-false.png" width="30px"/>'+
            '<img src="'+Constant.cdnContentPath+'/static/image/detail/collection2-2x-false.png" width="30px"/>'+
            '<img src="'+Constant.cdnContentPath+'/static/image/detail/collection2-2x-false.png" width="30px"/>'+
            '</div><br/>' +
            '<textarea class="form-control" id="order-remarks-content" rows="5" placeholder="请输入您的评论"></textarea>'+
            '</div>',
            buttons: [
                {
                    text: '取消'
                },
                {
                    text: '确定',
                    close:'false',
                    onClick:function(){
                        var label = $("#order-content-evaluate img");
                        var score = 0 ;
                        for(var i = 0 ; i<label.length ; i++){
                            if($(label[i]).attr("src").indexOf("true.png") != -1){
                                score = score+2;
                            }
                        }
                        var content = $("#order-remarks-content").val();
                        var para = {
                            typeId:typeId,
                            targetId:targetId,
                            orderNumber:orderNumber,
                            score:score,
                            content:content
                        }
                        myApp.showPreloader('正在提交......');
                        $.post(Constant.ctx("/mulanweb/evaluate/save"),para,function(info){
                            if(info.ReturnCode == 1){
                                mainView.router.refreshPage();
                            }
                            myApp.hidePreloader();
                            myApp.alert(info.AlertMessage, '新西兰微助手提醒你');
                        })

                    }
                }
            ]
        });
        $("#order-content-evaluate img").on("click",function(){
            var src = $(this).attr("src");
            if(src.indexOf("true.png") != -1){
                var nextElement = $(this).next();
                while (nextElement.attr("src")) {
                    nextElement.attr('src', nextElement.attr("src").replace('true.png', 'false.png'));
                    nextElement = nextElement.next();
                }
            }else{
                $(this).attr("src",$(this).attr("src").replace('false.png', 'true.png'));
                var prevElement = $(this).prev();
                while (prevElement.attr("src")) {
                    prevElement.attr('src', prevElement.attr("src").replace('false.png', 'true.png'));
                    prevElement = prevElement.prev();
                }
            }
        })
    } else if (statusId == 8) {
        //查看评论
        var para = {
            typeId:typeId,
            targetId:targetId,
            orderNumber:orderNumber,
        }
        $.post(Constant.ctx("/mulanweb/evaluate/getUserRemarks"),para,function(info){
            if(info.ReturnCode == 1){
                if(info.DataList.Score){
                    var img = [] ;
                    var i = 0 ;
                    while(i<(info.DataList.Score/2)){
                        img.push('<img src="'+Constant.cdnContentPath+'/static/image/detail/collection-2x-true.png" width="25px"/>');
                        i++;
                    }
                    i=img.length;
                    while(i<5){
                        img.push('<img src="'+Constant.cdnContentPath+'/static/image/detail/collection-2x-false.png" width="25px"/>');
                        i++;
                    }
                }
                var modal = myApp.modal({
                    text: '<div style="padding:140px 20px 0px 20px;text-align: center;background:url(../../../static/image/order/modelBackground-1x.png) no-repeat 0px 0px ; width:270px; height: auto;">' +
                    '<div style="width:100%;height:25px" id="order-content-evaluate">'+
                    img.join("")+
                    '</div><br/>' +
                    '<textarea class="form-control" rows="5" readonly="readonly">'+info.DataList.Content+'</textarea>'+
                        info.DataList.CreateTime+
                    '</div>',
                    buttons: [
                        {
                            text: '确定'
                        }
                    ]
                });

            }else{
                myApp.alert(info.ReturnStr||info.AlertMessage||'操作失败','新西兰微助手');
            }
        })
    }
    myApp.hidePreloader();
}
function applyRefund(orderNumber){
    myApp.confirm('您确定要退款吗？',"新途微助手", function () {
        myApp.showPreloader('正在申请......');
        var para={
            orderNumber:orderNumber
        }
        $.post(Constant.ctx("/mulanweb/wechat/refund/applyRefund"),para,function(info){
            if(info.ReturnCode == 1){
                window.location.href="https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx1a5d74a8c7cb135e&redirect_uri=http%3a%2f%2fweixin.mulanweb.com%2fadmin%2ftest%2fgetAuthority&response_type=code&scope=snsapi_base&state=order#wechat_redirect";
            }else{
                myApp.alert(info.ReturnStr||'操作失败','新西兰微助手');
            }
        });
        setTimeout(function(){
            myApp.hidePreloader();
        },2000);
    });
}

function cancelOrder(orderNumber){
    myApp.confirm('',"您确定要取消订单吗？", function () {
        myApp.showPreloader('正在取消......');
        var para={
            orderNumber:orderNumber
        }
        $.post(Constant.ctx("/mulanweb/common/order/cancelOrder"),para,function(info){
            if(info.ReturnCode == 1){
                myApp.alert("",info.ReturnStr || info.AlertMessage,function(){
                    window.location.href="https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx1a5d74a8c7cb135e&redirect_uri=http%3a%2f%2fweixin.mulanweb.com%2fadmin%2ftest%2fgetAuthority&response_type=code&scope=snsapi_base&state=order#wechat_redirect";
                })
            }else{
                myApp.alert(info.ReturnStr||info.AlertMessage||'操作失败','新西兰微助手');
            }
        });
        setTimeout(function(){
            myApp.hidePreloader();
        },2000)
    });
}
